package com.dxy.mvc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class DispatcherServlet extends javax.servlet.http.HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        String path = config.getInitParameter("contentConfigLocation");
        InputStream inputStream = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
        HandlerMapping.Load(inputStream);


    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//告诉客户端应该以何种方式进行解码，即解析服务器发来的数据，保证解码编码方式相同，才能保证获得原来的数据而不出现乱码
        resp.setHeader("Content-type","text/html;charset=utf-8");

        //1.获取用户请求的uri
        String requestURI = req.getRequestURI();
        HandlerMapping.MVCMapping mvcMapping = HandlerMapping.get(requestURI);

        if (mvcMapping==null){
            resp.sendError(404,"自定义MVC:映射地址不存在"+requestURI);
        }
        Object object = mvcMapping.getObject();
        Method method = mvcMapping.getMethod();
        Object invoke=null;
        try {
             invoke = method.invoke(object, req, resp);
        }  catch (Exception e) {
            e.printStackTrace();
        }

        switch (mvcMapping.getResponseType()){
            case TEXT:
                resp.getWriter().write((String) invoke);
                break;
            case VIEW:
                resp.sendRedirect((String) invoke);
                break;

        }



    }
}
